package com.kun.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.kun.entity.ResponseJson;
import com.kun.entity.UserInfo;
import com.kun.service.UserInfoService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/user/{userId}")
    public ResponseJson<UserInfo> findById(@PathVariable("userId") Integer userId) {
        UserInfo userInfo = userInfoService.findById(userId);
        ResponseJson<UserInfo> result = new ResponseJson<>();
        if (userInfo == null) {
            result.setCode(500);
            result.setMsg("未找到数据");
        } else {
            result.setCode(200);
            result.setMsg("找到数据");
            result.setData(userInfo);
        }
        return result;
    }

    @GetMapping("/login/{userName}/{userPwd}/{verifyCode}")
    public ResponseJson<UserInfo> login(@PathVariable("userName") String userName
            , @PathVariable("userPwd") String userPwd
            , @PathVariable("verifyCode") String verifyCode
            , HttpServletRequest req) {
        //验证验证码
        UserInfo userInfo = null;
        String googleVerifyCode = (String) req.getSession().getAttribute("googleVerifyCode");
        if (!verifyCode.equals(googleVerifyCode)) {
            ResponseJson result = new ResponseJson();
            result.setCode(500);
            result.setMsg("验证码不一致");
            return result;
        }
        userInfo = userInfoService.login(userName, userPwd);
        if (userInfo == null) {
            ResponseJson result = new ResponseJson();
            result.setCode(500);
            result.setMsg("用户名密码错误");
            return result;
        }else {

        req.getSession().getServletContext().setAttribute("userName", userName);
        ResponseJson result = new ResponseJson();
        result.setCode(200);
        result.setMsg("登陆成功");
        return result;
        }
    }

    ;

    @GetMapping("/findByPage")
    public ResponseJson<Map> findByPages(@RequestParam("page") Integer pageNum
            , @RequestParam("limit") Integer pageSize
            , UserInfo userInfo) {
        Map<String, Object> data = userInfoService.selectByPage(pageNum, pageSize, userInfo);
        ResponseJson<Map> result = new ResponseJson<>();
        if (data != null) {
            result.setCode(200);
            result.setMsg("查询成功");
            result.setData(data);
        } else {
            result.setCode(500);
            result.setMsg("查询失败");
        }
        return result;
    }

    @PostMapping("/insert")
    public ResponseJson<UserInfo> insertUser(UserInfo userInfo) {
        ResponseJson<UserInfo> result = new ResponseJson<>();
        int ui = userInfoService.insertUser(userInfo);
        if (ui == 0) {
            result.setCode(500);
            result.setMsg("添加失败");
        }
        result.setCode(200);
        result.setMsg("添加成功");
        return result;
    }

    @DeleteMapping("/batchDelete")
    public ResponseJson batchDelete(Integer[] userIds) {
        ResponseJson<UserInfo> result = new ResponseJson<>();
        if (userInfoService.batchDelete(userIds) > 0) {
            result.setCode(200);
            result.setMsg("删除成功");
        } else {
            result.setCode(500);
            result.setMsg("删除失败");
        }
        return result;
    }

    @PutMapping("/updateUser")
    public ResponseJson updateUser(UserInfo userInfo) {
        ResponseJson<UserInfo> result = new ResponseJson<>();
        if (userInfoService.updateUser(userInfo) > 0) {
            result.setCode(200);
            result.setMsg("更新成功");
        } else {
            result.setCode(500);
            result.setMsg("更新失败");
        }
        return result;
    }

    @GetMapping("/exportExcel")
    public void exportExcel(UserInfo userInfo, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息.xls", "UTF-8"));

        List<UserInfo> list = userInfoService.exportExcel(userInfo);

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户信息", "测试", "用户数据"),
                UserInfo.class, list);

        ServletOutputStream out = response.getOutputStream();

        workbook.write(out);

        out.flush();

        out.close();
    }

    @GetMapping("/findUser")
    public ResponseJson<List> findUserName() {
        ResponseJson<List> result = new ResponseJson<>();
        List<UserInfo> data = userInfoService.findUserName();
        if (data != null) {
            result.setCode(200);
            result.setMsg("查询成功");
            result.setData(data);
        } else {
            result.setCode(500);
            result.setMsg("查询失败");
        }
        return result;

    }

    @RequestMapping("/logout")
    public void logout(HttpSession session) {
        String userName = (String) session.getServletContext().getAttribute("userName");
        if (userName != null) {
            session.getServletContext().removeAttribute("userName");
        }
    }
}

